package servlet;

import anno.RequestBody;
import anno.ResponseBody;
import dao.UserDAO;
import pojo.UpdatePasswordVO;
import pojo.User;
import utils.ApiResult;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.Map;

@WebServlet("/user")
public class UserServlet extends BaseServlet {
    private final UserDAO userDAO = new UserDAO();

    @ResponseBody
    public ApiResult register(HttpServletRequest req, HttpServletResponse resp, @RequestBody User user) throws SQLException {
        // 检查用户名是否已存在
        User existingUser = userDAO.findByUsername(user.getUsername());
        if (existingUser != null) {
            return new ApiResult(400, "用户名已存在", null);
        }

        // 设置默认值
        if (user.getFullname() == null) {
            user.setFullname("默认：" + user.getUsername());
        }
        if (user.getRoleType() == null) {
            user.setRoleType("user");
        }
        if (user.getEmail() == null) {
            user.setEmail("default@example.com");
        }
        if (user.getPhoneNumber() == null) {
            user.setPhoneNumber("15078012385");
        }
        if (user.getAddress() == null) {
            user.setAddress("....");
        }
        if (user.getBio() == null) {
            user.setBio("...");
        }
        user.setCreatedAt(LocalDateTime.now());
        user.setLastLogin(LocalDateTime.now());
        // 注册用户,默认需要审核
        user.setIsActive("false");
        userDAO.register(user);
        return new ApiResult(200, "用户注册成功", null);
    }


    // UserServlet.java

    @ResponseBody
    public ApiResult login(HttpServletRequest req, HttpServletResponse resp, @RequestBody User user) throws SQLException {
        User login = userDAO.login(user.getUsername(), user.getPassword());
        if (login != null) {
            if (!"true".equals(login.getIsActive())) { // 检查 isActive 状态
                return new ApiResult(403, "用户尚未激活，请等待管理员审批", null);
            }

            // 更新用户的 last_login 字段
            login.setLastLogin(LocalDateTime.now());
            userDAO.updateUser(login);

            return new ApiResult(200, "登录成功", login);
        } else {
            return new ApiResult(404, "用户名或密码错误", null);
        }
    }


    @ResponseBody
    public ApiResult updatePassword(HttpServletRequest req, HttpServletResponse resp, @RequestBody UpdatePasswordVO updatePasswordVO) throws SQLException {
        User user = userDAO.findByUsername(updatePasswordVO.getUsername());
        if (user == null || !user.getPassword().equals(updatePasswordVO.getOldPassword())) {
            return new ApiResult(400, "用户名或旧密码错误", null);
        }

        userDAO.updatePassword(updatePasswordVO.getUsername(), updatePasswordVO.getNewPassword());
        return new ApiResult(200, "密码修改成功", null);
    }

    @ResponseBody
    public ApiResult getAllUsers(HttpServletRequest req, HttpServletResponse resp) throws SQLException {
        return new ApiResult(200, "查询所有用户成功", userDAO.findAllUsers());
    }

    @ResponseBody
    public ApiResult findUsersByPageAndName(HttpServletRequest req, HttpServletResponse resp, String keyword, String pageNum, String pageSize) throws SQLException {
        int page = Integer.parseInt(pageNum);
        int size = Integer.parseInt(pageSize);
        Map<String, Object> result = userDAO.findUsersByPageAndName(keyword, page, size);
        return new ApiResult(200, "分页模糊查询用户成功", result);
    }

    @ResponseBody
    public ApiResult updateUser(HttpServletRequest req, HttpServletResponse resp, @RequestBody User user) throws SQLException {
        userDAO.updateUser(user);
        return new ApiResult(200, "更新用户信息成功", null);
    }

    @ResponseBody
    public ApiResult deleteUser(HttpServletRequest req, HttpServletResponse resp, String userId) throws SQLException {
        userDAO.deleteUser(Long.valueOf(userId));
        return new ApiResult(200, "删除用户成功", null);
    }

    // 重置密码方法
    @ResponseBody
    public ApiResult resetPassword(HttpServletRequest req, HttpServletResponse resp, @RequestBody UpdatePasswordVO resetPasswordVO) throws SQLException {
        User user = userDAO.findByUsername(resetPasswordVO.getUsername());
        if (user == null) {
            return new ApiResult(404, "用户不存在", null);
        }

        userDAO.updatePassword(resetPasswordVO.getUsername(), resetPasswordVO.getNewPassword());
        return new ApiResult(200, "密码重置成功", null);
    }
}
